﻿using System;
using System.Drawing;
using System.Windows.Forms;
using AMM.Model;
using AMM.UserControls;

namespace AMM.Forms {
    public partial class FrmSearch : FrmRootBase {

        #region Search event

        public delegate void SearchEventHandler(object sender, SearchArgs e);
        public event SearchEventHandler Search;
        public void OnSearch(object sender, SearchArgs e) {
            if (this.Search != null) {
                this.Search(sender, e);
            }
        }

        public class SearchArgs : EventArgs {
            public BaseSearchModel SearchModel { get; set; }
            public bool IsRevert { get; set; }
        }

        #endregion

        public FrmSearch() {
            InitializeComponent();
        }

        private BaseSearchControl GetSearchControl() {
            BaseSearchControl searchControl = new BaseSearchControl();
            foreach (Control c in this.Controls) {
                if (c is BaseSearchControl) {
                    searchControl = (BaseSearchControl)c;
                    break;
                }
            }
            return searchControl;
        }

        private void btnSearch_Click(object sender, EventArgs e) {
            BaseSearchControl searchControl = this.GetSearchControl();
            this.OnSearch(this, new SearchArgs {
                SearchModel = searchControl.GetSearchModel(),
                IsRevert = false
            });
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e) {
            BaseSearchControl searchControl = this.GetSearchControl();
            searchControl.ResetSearchModel();
            this.OnSearch(this, new SearchArgs {
                SearchModel = new BaseSearchModel(),
                IsRevert = true
            });
            this.Close();
        }

        private void FrmSearch_ControlAdded(object sender, ControlEventArgs e) {
            BaseSearchControl searchControl = this.GetSearchControl();
            this.Bounds = searchControl.Bounds;
            searchControl.Location = new Point(0, 10);
            this.Height += this.pnlBtn.Height * 2 + 30;
            this.Width = (this.Width <= this.pnlBtn.Width ? this.pnlBtn.Width : this.Width) + 10;
            this.pnlBtn.Location = new Point((searchControl.Width - this.pnlBtn.Width) / 2, searchControl.Top + searchControl.Height + 10);
        }
    }
}
